import { View, Picker } from "@tarojs/components";
import {
  AtList,
  AtListItem,
  AtForm,
  AtInput,
  AtButton,
  AtMessage
} from "taro-ui";
import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { addProjectUserApi } from "../../../utils/api";

// 1-操作工；2-配置员；3-管理员
const selector = [
  {
    type: 1,
    name: "操作工"
  },
  {
    type: 2,
    name: "配置员"
  },
  {
    type: 3,
    name: "管理员"
  }
];

const Index = () => {
  const project_id = useRouter().params.id;

  const [state, setState] = useState({
    mobile: "",
    role: {
      type: 1,
      name: "操作工"
    }
  });

  const changemobile = value => {
    setState(state => ({
      ...state,
      mobile: value
    }));
  };

  const changerole = e => {
    setState(state => ({
      ...state,
      role: selector[e.detail.value]
    }));
  };

  const onSubmit = async () => {
    const reg = /^1[3456789]\d{9}$/;
    if (reg.test(state.mobile)) {
      const res = await addProjectUserApi({
        project_id: project_id,
        mobile: state.mobile,
        role: state.role.type
      });
      if (res.res === 0) {
        Taro.atMessage({
          message: "新增成功",
          type: "success"
        });
        Taro.navigateBack({
          delta: 1
        });
      } else {
        Taro.atMessage({
          message: res.msg,
          type: "warning"
        });
      }
    } else {
      Taro.atMessage({
        message: "手机号格式错误",
        type: "error"
      });
    }
  };

  return (
    <View className="lonlat">
      <AtForm>
        <AtInput
          name="mobile"
          title="手机号"
          type="number"
          placeholder="请输入手机号"
          value={state.mobile}
          onChange={changemobile}
        />

        <Picker
          mode="selector"
          range={selector}
          rangeKey="name"
          onChange={changerole}
        >
          <AtList>
            <AtListItem title="用户角色" extraText={state.role.name} />
          </AtList>
        </Picker>

        <AtButton type="primary" onClick={onSubmit}>
          提交
        </AtButton>
      </AtForm>
      <AtMessage />
    </View>
  );
};

export default Index;
